import 'package:calendar_view/calendar_view.dart';
import 'package:flutter/material.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_execute_record.dart';
import 'package:schedule_self_client/utils/time_util.dart';

class CalendarPage extends StatefulWidget {
  const CalendarPage({super.key});

  @override
  State<CalendarPage> createState() => _CalendarPageState();
}

class _CalendarPageState extends State<CalendarPage>
    with
        AutomaticKeepAliveClientMixin<CalendarPage>,
        SingleTickerProviderStateMixin {
  final _eventController = EventController();

  late List<TaskExecuteRecord> _taskExecuteRecordList;

  final _dayViewKey = GlobalKey<DayViewState>();

  late final TabController _tabController =
      TabController(vsync: this, length: 3);

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _getTaskExecuteRecordList(null);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            flexibleSpace: const TabBar(
              dividerHeight: 0.0,
              indicatorSize: TabBarIndicatorSize.label,
              tabs: [
                Tab(
                  text: '日',
                ),
                Tab(
                  text: '周',
                ),
                Tab(
                  text: '月',
                ),
              ],
            ),
            backgroundColor: Colors.transparent,
            elevation: 0.0,
          ),
          body: CalendarControllerProvider(
            controller: _eventController,
            child: TabBarView(
              children: [
                DayView(
                  key: _dayViewKey,
                  onPageChange: (DateTime date, int page) {
                    _getTaskExecuteRecordList(date);
                  },
                  backgroundColor: Theme.of(context).colorScheme.surface,
                  headerStyle: HeaderStyle(
                    decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.surfaceContainer),
                  ),
                  showHalfHours: false,
                  showVerticalLine: true,
                  heightPerMinute: 2,
                ),
                WeekView(
                  backgroundColor: Theme.of(context).colorScheme.surface,
                  headerStyle: HeaderStyle(
                    decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.surfaceContainer),
                  ),
                  heightPerMinute: 2,
                ),
                MonthView(
                  headerStyle: HeaderStyle(
                    decoration: BoxDecoration(
                        color: Theme.of(context).colorScheme.surfaceContainer),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  void _getTaskExecuteRecordList(DateTime? dateTime) async {
    DateTime currDate = dateTime ?? DateTime.timestamp();

    final currIndex = _tabController.index;
    if (currIndex == 0) {
      DateTime startTime = DateTime(currDate.year, currDate.month, currDate.day)
          .subtract(TimeUtil.getTimeZoneOffsetDuration());
      DateTime endTime = startTime.add(const Duration(days: 1));
      TaskExecuteRecordListResp resp = await TaskApi.getTaskExecuteRecordList(
          TimeUtil.formatTimeToBackend(startTime),
          TimeUtil.formatTimeToBackend(endTime));
      _taskExecuteRecordList = resp.data;
      for (var record in _taskExecuteRecordList) {
        record.splitMultipleDays().forEach((item) {
          _eventController.add(TaskExecuteRecord.convert(item, context));
        });
      }
    }
  }
}
